# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         testsuite2testcase.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/26 9:16
# -------------------------------------------------------------------------------
from django.db import transaction
from rest_framework import status
from rest_framework.mixins import CreateModelMixin, ListModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from apps.HttpAutoTestService.filters import Testsuite2TestcaseFilter
from apps.HttpAutoTestService.models import Testsuite2Testcase
from apps.HttpAutoTestService.serializers import Testsuite2TestcaseSerializer

__all__ = ['Testsuite2TestcaseViewSet']


class Testsuite2TestcaseViewSet(CreateModelMixin, ListModelMixin, GenericViewSet):
    """
    组织场景用例
    """
    queryset = Testsuite2Testcase.objects.filter()
    serializer_class = Testsuite2TestcaseSerializer
    filter_class = Testsuite2TestcaseFilter
    pagination_class = None

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        testsuite2testcase = request.data
        testsuite_id = testsuite2testcase.get('testsuite_id') if testsuite2testcase else None
        data = testsuite2testcase.get('data') if testsuite2testcase else []
        Testsuite2Testcase.objects.filter(testsuite_id=testsuite_id).delete()
        testsuite2testcase_list = [Testsuite2Testcase(**item) for item in data]
        Testsuite2Testcase.objects.bulk_create(testsuite2testcase_list)
        return Response(status=status.HTTP_201_CREATED, content_type='application/json')
